import React, { useCallback, useState, useEffect } from "react";
import { NextPage } from "next";
import cls from "classnames";

import style from "./index.module.scss";
import { Recommend } from "@/components/Recommend";
import { Categories } from "@/components/Categories";
import { Tags } from "@/components/Tags";
import { Footer } from "@/components/Footer";
import { useAffix } from "@/components/Header/useAffix";
import { ArticleApi } from "@/api/article";
import { Icon } from "antd";
import dayjs from "dayjs";
import Link from "next/link";

const MonthList = ({ month, articles }) => {
  return (
    <div className={style.month}>
      <h3 className={style.monthName}>{month}</h3>
      <ul className={style.articleList}>
        {articles.map(a => (
          <li key={a.id} className={style.articleItem}>
            <Link href={"/article/[id]"} as={`/article/${a.id}`}>
              <a>
                <span className={style.day}>
                  {dayjs(a.publishAt).format("MM-DD")}
                </span>
                <p className={style.title}>{a.title}</p>
              </a>
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
};

const Archives: NextPage = porps => {
  const { categorys, tags, setting, archives } = porps as any;
  // const [affix, affixVisible] = useAffix(64, true);
  const totalCount = archives => {
    let count = 0;
    for (let year in archives) {
      for (let month in archives[year]) {
        count += archives[year][month].length;
      }
    }
    return count;
  };
  return (
    <div className={style.wrapper}>
      <div className="container">
        <div className={style.content}>
          <div className={style.head}>
            <Icon className={style.icon} type="blok" />
            <p>
              <span className={style.primary}>归档</span>共
              <span className={style.primary}>{totalCount(archives)}</span>
              篇文章
            </p>
          </div>
          <div className={style.list}>
            {Object.keys(archives).map(year => (
              <div className={style.year} key={year}>
                <h2>{year}</h2>
                {Object.keys(archives[year]).map(month => (
                  <MonthList
                    key={month}
                    month={month}
                    articles={archives[year][month]}
                  />
                ))}
              </div>
            ))}
          </div>
          <aside className={cls(style.aside)}>
            <div /**className={cls(affix ? style.affix : null)} */>
              <Recommend />
              <Categories categorys={categorys} />
              <Tags tags={tags} />
              <Footer setting={setting} />
            </div>
          </aside>
        </div>
      </div>
    </div>
  );
};

Archives.getInitialProps = async ctx => {
  const data = await ArticleApi.getArchives();
  return { archives: data, needLayoutFooter: false };
};

export default Archives;
